/** 
 * Creator:     JYW
 * CreatDate:   2019-04-17
 * descripts：  病人列表组件 护士执行，领药审核，生命体征可复用
*/
import React from 'react';
import { Row, Col, Tree, Select, Table, Input, Tooltip, Icon, Radio } from 'antd';
import { $http } from '../../../containers/config/https';
import ColumnAuthoritysModel from '../../columnAuthority/ColumnAuthoritysModel';
import store from '../../../store';
import './style/index.less'

let user;
class PatientList extends React.Component {
    constructor(props) {
        user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        var patientData = window.sessionStorage.patientData ? JSON.parse(window.sessionStorage.patientData) : {};
        super(props)
        this.state = {
            admID: "",
            iconType: "double-left",
            columns: [],
            wardList: [],
            selectWardID: "",
            checkedKeys: [],
            patientList: [],
            patientAll: [],
            icon: [],
            group: [],
            selectGroup: '',
            selectIcon: '',
            selectPatient: [],
            searchInput: "",
            type: "checkbox",
            patientData: patientData,
            visible: false,
            totalWidth: '',
            ENObj: {},
            CNObj: {},
        }
    }

    onCheck = (checkedKeys) => {
        this.setState({ checkedKeys });
    }

    componentDidMount() {
        if (this.props.onRef) {
            this.props.onRef(this);
        }
        this.getLocLinkLoc();
        this.loadColumn();

        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
    }

    componentWillUnmount() {
        this.setState = (state, callback) => {
            return
        }
    }

    loadColumn = () => {
        let data = {
            params: [{
                reactCode: ['InPatientList'],
                compontName: 'InPatientList',
                type: 'C',
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    let column = res.result.C;
                    if (user.language == 'EN') {
                        for (let i = 0; i < column.length; i++) {
                            column[i].title = column[i].enDescripts
                        }
                    }
                    this.setState({
                        columns: res.result.C,
                        totalWidth: res.totalWidth,
                        ENObj: res.result.language.EN,
                        CNObj: res.result.language.CN
                    })
                }
            }
        })
    }

    getLocLinkLoc = () => {
        let data = {
            params: [{
                type: "",
                hospID: user.hospID,
                locID: user.locID,
                detailFlag: "",
                linkFlag: "1",
                docFlag: ""
            }]
        }
        $http.post('urlDeault', this, {
            code: "04020008",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    let wardList = []
                    for (let i = 0; i < res.result.Data.length; i++) {
                        let obj = res.result.Data[i];
                        if (obj.locTypeCode === "W") {
                            wardList.push(obj);
                        }
                        for (let j = 0; j < obj.linkLoc.length; j++) {
                            let linkObj = obj.linkLoc[j];
                            if (linkObj.locTypeCode === "W") {
                                wardList.push(linkObj);
                            }
                        }

                    }
                    let wardID = wardList[0].id;
                    this.setState({
                        wardList: wardList,
                        selectWardID: wardID,
                    }, () => {
                        this.getPatients();


                        let admID = this.state.patientData.admID ? this.state.patientData.admID : "";
                        // console.log(admID)
                        if (admID) {
                            //    console.log("1111111",this.state.admID)
                            let selectPatient = [];
                            selectPatient.push(admID + '');
                            setTimeout(() => {
                                this.setState({
                                    selectPatient,
                                }, () => {
                                    this.props.updateState({ patient: selectPatient });
                                })
                            }, 300)
                        }
                    });
                } else {
                    message.error('获取病区失败!:' + res.errorMessage);
                }
            }
        })
    }

    loadTransLoc = () => {
        let data = {
            params: [{
                wardID: user.locID,
                roomType: "TransOut",
            }]
        }
        $http.post('urlDeault', this, {
            code: "04020002",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    let patientList = [], group = [];
                    // for (var i = 0; i < res.result.bedList.length; i++) {
                    //     let groupObj = res.result.bedList[i];
                    //     let obj = {};
                    //     obj.id = groupObj.id;
                    //     obj.code = groupObj.code;
                    //     obj.descripts = groupObj.descripts;
                    //     group.push(obj);
                    //     for (var j = 0; j < groupObj.bedList.length; j++) {
                    //         let admInfo = groupObj.bedList[j].patInfo.admInfo;
                    //         let patient = groupObj.bedList[j].patInfo.basicInfo;
                    //         Object.assign(patient, admInfo);
                    //         patient.groupId = groupObj.id;
                    //         patientList.push(patient);
                    //     }
                    // }
                    // if (res.result.waitPat !== undefined) {
                    //     let obj = {};
                    //     obj.id = res.result.waitPat.id;
                    //     obj.code = res.result.waitPat.code;
                    //     obj.descripts = res.result.waitPat.descripts;
                    //     group.push(obj);
                    //     for (var j = 0; j < res.result.waitPat.bedList.length; j++) {
                    //         let admInfo = res.result.waitPat.bedList[j].admInfo;
                    //         let patient = res.result.waitPat.bedList[j].basicInfo;
                    //         Object.assign(patient, admInfo);
                    //         patient.groupId = res.result.waitPat.id;
                    //         patientList.push(patient);
                    //     }
                    // }
                    this.setState({
                        patientList: patientList,
                        patientAll: patientList,
                        group: group,
                        selectPatient: [],
                    });
                    this.props.updateState({ patient: [] });
                } else {
                    message.error('未获取到病人列表：' + res.errorMessage);
                }
            }
        })
    }

    getPatients = () => {
        let data = {
            params: [{
                wardID: this.state.selectWardID,
                emptyFlag: "2",
            }]
        }
        $http.post('urlDeault', this, {
            code: "04020004",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    let patientList = [], group = [];
                    for (var i = 0; i < res.result.bedList.length; i++) {
                        let groupObj = res.result.bedList[i];
                        let obj = {};
                        obj.id = groupObj.id;
                        obj.code = groupObj.code;
                        obj.descripts = groupObj.descripts;
                        group.push(obj);
                        for (var j = 0; j < groupObj.bedList.length; j++) {
                            let admInfo = groupObj.bedList[j].patInfo.admInfo;
                            let patient = groupObj.bedList[j].patInfo.basicInfo;
                            Object.assign(patient, admInfo);
                            patient.groupId = groupObj.id;
                            patientList.push(patient);
                        }
                    }
                    if (res.result.waitPat !== undefined) {
                        let obj = {};
                        obj.id = res.result.waitPat.id;
                        obj.code = res.result.waitPat.code;
                        obj.descripts = res.result.waitPat.descripts;
                        group.push(obj);
                        for (var j = 0; j < res.result.waitPat.bedList.length; j++) {
                            let admInfo = res.result.waitPat.bedList[j].admInfo;
                            let patient = res.result.waitPat.bedList[j].basicInfo;
                            Object.assign(patient, admInfo);
                            patient.groupId = res.result.waitPat.id;
                            patientList.push(patient);
                        }
                    }
                    this.setState({
                        patientList: patientList,
                        patientAll: patientList,
                        group: group,
                        icon: res.result.bedIcon,
                    });
                    //this.props.updateState({ patient: [] });
                } else {
                    message.error('未获取到病人列表：' + res.errorMessage);
                }
            }
        })
    }

    onSelectChange = (flag, value) => {
        if (flag === "selectWardID") {
            this.setState({
                [flag]: value,
                selectGroup: '',
                selectIcon: '',
                selectPatient: [],
                searchInput: "",
            }, () => {
                this.getPatients();
            })
        } else {
            if (value === undefined) { value = ""; }
            let patientList = [];
            let selectGroup = this.state.selectGroup;
            let selectIcon = this.state.selectIcon;
            if ("selectGroup" === flag) {
                selectGroup = value;
            } else {
                selectIcon = value;
            }
            for (var i = 0; i < this.state.patientAll.length; i++) {
                let patientInfo = this.state.patientAll[i];
                let iconList = patientInfo.admIcon
                let findIcon = false, findGroup = false;
                if (selectIcon === "") { findIcon = true; }
                else {
                    for (var j = 0; j < iconList.length; j++) {
                        let iconObj = iconList[j];
                        if ((iconObj.id + "") === selectIcon) {
                            findIcon = true;
                        }
                    }
                }
                if (selectGroup === "") { findGroup = true; }
                else {
                    if ((patientInfo.groupId + "") === selectGroup) {
                        findGroup = true;
                    }
                }
                if (findIcon && findGroup) patientList.push(patientInfo);


            }
            this.setState({
                patientList: patientList,
                [flag]: value
            })
        }
    }

    /** 快捷筛选 */
    filterOption = (input, option) => {
        return ((option.props.descripts.toLowerCase().indexOf(input.toLowerCase()) >= 0) || (option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0))
    }
    
    onSearchInputChange = (e) => {
        this.setState({
            searchInput: e.target.value,
        })
    }

    ///登记号等查询条件回车事件
    // onSearchInputEnter = (e) => {
    //     e.stopPropagation();
    //     let searchValue = this.state.searchInput;
    //     let patientList = [];
    //     for (var i = 0; i < this.state.patientAll.length; i++) {
    //         let patientObj = this.state.patientAll[i];
    //         if ((patientObj.patName.indexOf(searchValue) > -1) || (patientObj.admBedCode.indexOf(searchValue) > -1) || (patientObj.patNo.indexOf(searchValue) > -1)) {
    //             patientList.push(patientObj);
    //         }
    //     }
    //     this.setState({
    //         patientList: patientList,
    //     });
    // }

    ///登记号等查询条件回车事件
    onSearchInputEnter = (e) => {
        e.stopPropagation();
        let searchValue = this.state.searchInput;
        if (searchValue != '') {
            let patientList = [];
            for (var i = 0; i < this.state.patientAll.length; i++) {
                let patientObj = this.state.patientAll[i];
                if ((patientObj.patName.indexOf(searchValue) > -1) || (patientObj.admBedCode.indexOf(searchValue) > -1) || (patientObj.patNo.indexOf(searchValue) > -1)) {
                    patientList.push(patientObj);
                }
            }
            let data = {
                params: [{
                    input: searchValue
                }]
            }
            $http.post('urlDeault', this, {
                code: "04020022",
                data: data,
                success: (res) => {
                    if (+res.errorCode === 0) {
                        let patList = res.result;
                        patientList = [...patList, ...patientList]
                        let obj = {}
                        let arr = patientList.reduce((cur, next) => {
                            obj[next.admID] ? "" : obj[next.admID] = true && cur.push(next);
                            return cur;
                        }, [])
                        this.setState({
                            patientList: arr
                        });
                    } else {
                        message.error('未获取到病人列表：' + res.errorMessage);
                    }
                }
            })
        } else {
            this.setState({
                patientList: this.state.patientAll
            });
        }
    }

    ///行背景色
    setRowClassName = (record) => {
        if (this.state.selectPatient.length === 0) {
            return '';
        }
        return record.admID === this.state.selectPatient[0] ? 'clickRowStyle' : '';
    }
    /** 去重  */
    unique5(arr) {
        var x = new Set(arr);
        return [...x];
    }
    onTableRow = (record) => {
        return {
            onClick: (event) => {
                let selectPatient = this.state.selectPatient;
                if (this.props.type !== "radio") {
                    let findFlag = false;
                    let start = 0;
                    selectPatient.find(function (value, key) {
                        if (value == record.admID) {
                            //遍历找到选中的数据，并记录下选中数据在数组中的key
                            findFlag = true;
                            start = key;
                        }
                    })
                    if (findFlag) {
                        //再次点击移除选中
                        selectPatient.splice(start, 1);
                    }
                    else {
                        //将点击的行添加到选中
                        selectPatient.push(record.admID);
                    }
                    this.setState({ selectPatient: selectPatient });
                    this.props.updateState({ patient: selectPatient, selectPatient: record });
                } else {
                    let selectPatient = [];
                    selectPatient.push(record.admID);
                    this.setState({ selectPatient: selectPatient });
                    this.props.updateState({ patient: selectPatient, selectPatient: record });
                }
            },
        };

    }
    onMenuFoldClick = (e) => {
        let obj = {};
        if (this.props.iconType != "double-left") {
            obj.leftspan = 5;
            obj.rightspan = 19;
            obj.iconType = "double-left"
            this.props.updateState(obj);
        }
        else {
            obj.leftspan = 1;
            obj.rightspan = 23;
            obj.iconType = "double-right"
            this.props.updateState(obj);

        }

    }
    onColumnRef = (ref) => {
        this.columnRef = ref;
    }
    renderColItem = (col, colIndex, text, record, index) => {
        let obj = {
            children: text,
            props: {
                style: {}
            },
        };
        obj.props.style.width = col.width;
        if (col.code == "icon") {
            let icon = record.admIcon.map(
                (item) => {
                    return (
                        <div
                            title={item.title}
                            className="bedicon"
                            style={{
                                width: "18px",
                                height: "18px",
                                backgroundPosition: (-((item.position % 10 - 1) * 18)) + "px" + " " + (-(parseInt(+item.position / 10) * 18)) + "px"
                            }}
                        > </div>
                    );
                }
            );
            obj.children = icon
        } else {
            if(record.aclIfOrderExcute=="Y"){
                obj.children = <Tooltip placement="topLeft" title={text}><div style={{color:'#ff0000'}}>{text}</div></Tooltip> 
            }else{
                obj.children = <Tooltip placement="topLeft" title={text}>{text}</Tooltip>
            }
        }
        return obj;
    }

    handleChangeRadio(name, e) {
        this.setState({
            selectPatient:[]
        },()=>{
            this.props.updateState({ [name]: e.target.value });
        })
    }
    render() {
        const tableHeight = this.props.heights ? this.props.heights : store.getState().tableHeight.y + 298 - 190;
        const selection = {
            columnWidth: "35px",
            type: this.props.type !== undefined ? (this.props.activeKey == '2' ? 'checkbox' : this.props.type) : this.state.type,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ selectPatient: selectedRowKeys });
                this.props.updateState({ patient: selectedRowKeys });
            },
            selectedRowKeys: this.state.selectPatient,
        }
        let width = this.state.totalWidth.split("px")[0] || 300;
        width = Number(width);
        const columns = this.state.columns.map((col, colIndex) => {
            return {
                ...col,
                render: this.renderColItem.bind(this, col, colIndex),
            };
        });
        var language = user.language
        var languageObj = {}
        if (language == "EN") {
            languageObj = this.state.ENObj
        } else {
            languageObj = this.state.CNObj
        }
        console.dir(this.props.iconType)
        return (
            this.props.iconType == "double-left" ? (
                <Col className="patientList">
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName="InPatientList"
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.loadColumn}
                    />
                    <Row className="searchTitle">
                        <Col span={10}>
                            <span className='scheduling-title-border'></span>
                            <span style={{ marginLeft: 20 }}>{languageObj.InPatientListSearchPatients != null ? languageObj.InPatientListSearchPatients.descripts : ""}</span>
                        </Col>
                        <Col span={5} offset={9} style={{ width: "30px" }}>
                            <Icon className="foldIcon" style={{ fontSize: "18px", marginLeft: 51 }} type={this.props.iconType} onClick={this.onMenuFoldClick.bind(this)} />
                        </Col>
                    </Row>
                    <Row className="inputSearch">
                        <span>{languageObj.InPatientListPatNo != null ? languageObj.InPatientListPatNodescripts : ""}</span>
                        <Input
                            placeholder="床号/姓名/患者ID/住院号(回车查询)"
                            className="search"
                            value={this.state.searchInput}
                            onChange={this.onSearchInputChange}
                            onPressEnter={this.onSearchInputEnter}
                        />
                    </Row>
                    <div className="quickSearch">
                        <Row className="wardselect">
                            <span>{languageObj.InPatientListWard != null ? languageObj.InPatientListWard.descripts : ""}</span>
                            <Select
                                style={{ width: "84%" }}
                                value={this.state.selectWardID}
                                showSearch={true}
                                filterOption={this.filterOption}
                                onChange={this.onSelectChange.bind(this, "selectWardID")}>
                                {
                                    this.state.wardList.map(
                                        (item) => {
                                            return (
                                                <Select.Option
                                                    key={item.id}
                                                    descripts={item.descripts}
                                                >
                                                    {item.descripts}
                                                </Select.Option>
                                            )
                                        }
                                    )
                                }
                            </Select>
                        </Row>
                        <Row className="quikselect">
                            <Col span={12}  >
                                <span>{languageObj.InPatientListGroup != null ? languageObj.InPatientListGroup.descripts : ""}</span>
                                <Select
                                    style={{ width: "70%" }}
                                    allowClear={true}
                                    value={this.state.selectGroup}
                                    onSelect={this.onSelectChange.bind(this, "selectGroup")}
                                    onChange={this.onSelectChange.bind(this, "selectGroup")}>
                                    {
                                        this.state.group.map(
                                            (item) => {
                                                return (
                                                    <Select.Option key={item.id} descripts={item.descripts}>
                                                        {item.descripts}
                                                    </Select.Option>
                                                )
                                            }
                                        )
                                    }
                                </Select>
                            </Col>
                            <Col span={12}>
                                <span style={{ marginLeft: '16px' }}>{languageObj.InPatientListShort != null ? languageObj.InPatientListShort.descripts : ""}</span>
                                <Select
                                    style={{ width: "60%" }}
                                    allowClear={true}
                                    value={this.state.selectIcon}
                                    onChange={this.onSelectChange.bind(this, "selectIcon")}
                                    onSelect={this.onSelectChange.bind(this, "selectIcon")}
                                >

                                    {
                                        this.state.icon.map(
                                            (item) => {
                                                return (
                                                    <Select.Option key={item.id} descripts={item.descripts}>
                                                        {item.descripts}
                                                    </Select.Option>
                                                )
                                            }
                                        )
                                    }
                                </Select>
                            </Col>
                        </Row>
                    </div>

                    <Col className="patlistTitle">
                        <div style={{ height: '30px', lineHeight: '30px', fontSize: '14px', fontWeight: 'bold', marginLeft: '10px', float: 'left' }}>
                            {languageObj.InPatientListPatientList != null ? languageObj.InPatientListPatientList.descripts : ""}</div>

                        {this.props.check == 'checkbox' ? <div style={{ float: 'right', marginRight: 10 }}>
                            <Radio.Group value={this.props.activeKey} buttonStyle="solid" onChange={this.handleChangeRadio.bind(this, 'activeKey')}>
                                <Radio.Button value='1'>单选</Radio.Button>
                                <Radio.Button value='2'>多选</Radio.Button>
                            </Radio.Group>
                        </div> : null}
                    </Col>
                    <div style={{ height: 'calc(100% - 192px)', padding: '6px 11px 11px 11px' }}>
                        <Table
                            onHeaderRow={column => {
                                return {
                                    onDoubleClick: () => {
                                        this.columnRef.onOpenModel();
                                    },
                                };
                            }}
                            columns={columns}
                            rowSelection={this.props.type === "radio" ? (this.props.activeKey == '2' ? selection : null) : selection}
                            dataSource={this.state.patientList}
                            rowKey={(row) => {
                                return row.admID;
                            }}

                            rowClassName={this.setRowClassName}
                            onRow={this.onTableRow}
                            pagination={false}
                            bordered
                            scroll={{ x: width, y: 'scroll' }}
                        />
                    </div>
                </Col>
            )
                :
                <Icon className="openfoldIcon" style={{ fontSize: "18px", overflow: 'hidden', zIndex: '1000', height: '22px', width: '22px' }} type={this.props.iconType} onClick={this.onMenuFoldClick.bind(this)} />
        )
    }
}
export default PatientList